package com.usian.wemedia.gateway.filters;

import com.usian.utils.common.AppJwtUtil;
import io.jsonwebtoken.Claims;
import org.apache.commons.lang3.StringUtils;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * 类描述：
 *
 * @ClassName AuthorizeFilter
 * @Description TODO
 * @Author Jay
 * @Date 2022/11/11 18:57
 * @Version 1.0
 */

// @Slf4j
@Component
public class AuthorizeFilter implements GlobalFilter, Ordered {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {

        //获取resquest，response对象
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();

        //判断请求路径是否为login/in
        if (request.getURI().getPath().contains("/login/in")) {
            //放行
            return chain.filter(exchange);
        }

        //获取请求头信息中的token
        String token = request.getHeaders().getFirst("token");
        //校验token是否存在
        if (StringUtils.isEmpty(token)){
            //如果不存在 返回错误信息 让用户继续登录
            //UNAUTHORIZED 响应用户为鉴权
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }
        try {
            //解析token中的内容
            Claims claims = AppJwtUtil.getClaimsBody(token);
            //校验
            int i = AppJwtUtil.verifyToken(claims);
            //这两种情况说明token是在有效期的
            if (i==0 || i==-1){
                //合法，向header中设置userid
                Integer id = (Integer) claims.get("id");
                System.out.println(id);
                //
                //重新设置token到header中
                ServerHttpRequest serverHttpRequest = request.mutate().headers(httpHeaders -> {
                    httpHeaders.add("userid", id+"");
                }).build();
                //重新构建请求头信息
                exchange.mutate().request(serverHttpRequest).build();

            }
        } catch (Exception e) {
            e.printStackTrace();
            //向客户端返回错误提示信息
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();

        }

        //放行
        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
